package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    /**
     * 批量查询博客内容
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            blog.setIsLike(isLiked(blog.getId()));
        });
        return Result.ok(records);
    }

    /**
     * 根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);

        Long userId = blog.getUserId();
        User user = userService.getById(userId);

        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        blog.setIsLike(isLiked(id));
        return Result.ok(blog);
    }

    /**
     * 博客点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {

        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();
        Long userId = UserHolder.getUser().getId();
        String key = "blog:liked:"+id;

        //1.已经点赞
        if(isLiked(id).booleanValue()){
            //表明要取消点赞
            //修改数据库，将点赞数减一
            this.update()
                    .setSql("liked = liked - 1").eq("id", id).update();
            //删除redis中数据
            setOperations.remove(key, userId.toString());
        }else {
            //2.没有点赞
            //表明要点赞
            //修改数据库，将点赞数减
            this.update()
                    .setSql("liked = liked + 1").eq("id", id).update();
            //添加数据到redis
            setOperations.add(key, userId.toString());
        }

        return Result.ok();
    }

    /**
     * 查询点赞列表
     * @param id
     * @return
     */
    @Override
    public Result queryLikesById(Long id) {
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();
        //获取该博客的所有点赞人id
        Set<String> userIds = setOperations.members(SystemConstants.BLOG_LIKED + id);
        //根据用户id查询数据库
        List<User> users = userIds.stream().map(userService::getById).collect(Collectors.toList());
        //将user集合转换为userDTO集合
        List<UserDTO> userDTOs = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        return Result.ok(userDTOs);
    }

    /**
     * 发布博客
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        this.save(blog);
        //将博客信息推送到粉丝收件箱(feed流推模式)
        List<Follow> fans = followService.query().eq("follow_user_id", user.getId()).list();
        for (Follow fan : fans) {
            stringRedisTemplate.opsForZSet().add(RedisConstants.FEED_KEY+fan.getUserId(),blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 滚动分页查询已关注博主发布的博客
     * @param lastId
     * @param offset
     * @return
     */
    @Override
    public Result queryMyFollow(Long lastId, Integer offset) {
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();

        //查询对应数据 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(RedisConstants.FEED_KEY + userId, 0,lastId, offset, 2);

        //为空直接返回
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }

        //不为空，解析数据
        List<Long> blogIds = new ArrayList<>();
        Long minTimeMillis = System.currentTimeMillis();
        Integer thisOffset = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String blogId = typedTuple.getValue();
            blogIds.add(Long.parseLong(blogId));

            long timeMillis = typedTuple.getScore().longValue();
            if(timeMillis < minTimeMillis){
                minTimeMillis = timeMillis;
            }else if(timeMillis == minTimeMillis){
                thisOffset++;
            }
        }

        //查询完整博客数据
        List<Blog> blogs = new ArrayList<>();
        for (Long blogId : blogIds) {
            Blog blog = this.query().eq("id", blogId).one();
            Long userId1 = blog.getUserId();
            User user = userService.getById(userId1);

            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            blog.setIsLike(isLiked(userId));
            blogs.add(blog);
        }

        //封装返回数据
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(thisOffset);
        scrollResult.setMinTime(minTimeMillis);

        return Result.ok(scrollResult);
    }


    //判断当前用户是否已经对该博客点赞
    private Boolean isLiked(Long id){
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();
        Long userId = UserHolder.getUser().getId();
        String key = SystemConstants.BLOG_LIKED+id;

        if(userId == null){
            return Boolean.FALSE;
        }

        //判断当前用户是否已经对该博客点赞
        Boolean isLiked = setOperations.isMember(key, userId.toString());
        return isLiked;
    }
}
